package com.mabang.medata.util;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
/**
 * 
* @ClassName: XmlUtil 
* @Description: xml工具类
* @author yuyidi 
* @date 2015年4月1日 上午11:49:04
 */
public class XmlUtil
{
	private Document document = null;
	
	public XmlUtil(File xmlFile) throws Exception
	{
		SAXReader saxReader = new SAXReader(); 
		document = saxReader.read(xmlFile); 
	}
	public XmlUtil(String xmlStr) throws Exception
	{
		document = DocumentHelper.parseText(xmlStr); 
	}
	
	/**
	 * 获取根节点
	 * @return
	 * @throws Exception
	 */
	public Element getRootElement() throws Exception
	{
		return document.getRootElement();
	}
	/**
	 * 获取某个节点下，某个名字的子节点
	 * @param element
	 * @param childElementName
	 * @return
	 * @throws Exception
	 */
	public Element getChildElement(Element element,String childElementName) throws Exception
	{
		return element.element(childElementName);
	}
	/**
	 * 根据节点名称获取节点值
	 * @param nodeName
	 * @return
	 * @throws Exception
	 */
	public String getSingleElementValue(String nodeName) throws Exception
	{
		 String result = "";
		 Node node = document.selectSingleNode("//" + nodeName);
		 if(node != null)
		 {
			 result = node.getText();
		 }
		 return result;
	}
	/**
	 * 获取一个节点下某个子节点值 
	 * @param nodeName
	 * @param childNodeName
	 * @return
	 * @throws Exception
	 */
	public String getSingleChildElementValue(String nodeName, String childNodeName) throws Exception
	{
		 String result = "";
		 Node node = document.selectSingleNode("//" + nodeName + "/" + childNodeName);
		 if(node != null)
		 {
			 result = node.getText();
		 }
	     return result;
	}
	/**
	 * 获取某个节点的所有子节点 
	 * @param element
	 * @return
	 * @throws Exception
	 */
	public List <Element> getAllChildElements(Element element) throws Exception
	{   
	    List <Element> elements = element.elements();   
	    return elements;
	          
	} 
	/**
	 * 根据路径查找旗下所有节节点集合
	 * @param elementPath
	 * @return
	 * @throws Exception
	 */
	public  List <Element> getAllChildElementsByPath(String elementPath) throws Exception
	{
		 List <Element> list= document.selectNodes(elementPath); 
		 return list;
	}
	 


}
